package common

import (
	"errors"
	"im/internal/model"
	"im/pkg/databases"
	"time"
)

type Result struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Time int64  `json:"time"`
	Data any    `json:"data"`
}

func Response(res *Result) {
	panic(res)
}

func Success(args ...any) *Result {
	res := &Result{
		Code: 1,
		Msg:  "",
		Time: time.Now().Unix(),
		Data: nil,
	}
	if len(args) > 0 {
		if msg, ok := args[0].(string); ok {
			res.Msg = msg
		}
	}
	if len(args) > 1 {
		res.Data = args[1]
	}
	return res
}

func Error(args ...any) *Result {
	res := &Result{
		Code: 0,
		Msg:  "",
		Time: time.Now().Unix(),
		Data: nil,
	}
	if len(args) > 0 {
		if msg, ok := args[0].(string); ok {
			res.Msg = msg
		}
	}
	if len(args) > 1 {
		res.Data = args[1]
	}
	return res
}

func GetUserByToken(t string) (*model.User, error) {
	if t == "" {
		return nil, errors.New("token不能为空")
	}
	t = GetEncryptedToken(t)
	token := new(model.UserToken)
	result := databases.GetGorm().Where("token = ? ", t).First(token)
	if result.Error != nil {
		return nil, errors.New("无效令牌")
	}
	if token.Expiretime < time.Now().Unix() {
		return nil, errors.New("令牌已过期")
	}
	user := new(model.User)
	result = databases.GetGorm().Where("id = ?", token.UserID).First(user)
	if result.Error != nil {
		return nil, errors.New("用户不存在")
	}
	//异常用户
	if user.Status != "normal" {
		return nil, errors.New("用户状态异常")
	}
	return user, nil
}

// NewToken 生成一个新的token
func NewToken(token string, userId int, expire int64) (string, error) {
	var expiretime int64 = 0
	if expire != 0 {
		expiretime = time.Now().Unix() + expire
	}
	encrypted := GetEncryptedToken(token)
	result := databases.GetGorm().Create(&model.UserToken{
		Token:      encrypted,
		UserID:     userId,
		Createtime: time.Now().Unix(),
		Expiretime: expiretime,
	})
	if result.Error != nil {
		return "", result.Error
	}
	return encrypted, nil
}
